package cn.shuangze.assetsms.view;

import cn.shuangze.assetsms.component.MyJTable;
import cn.shuangze.assetsms.dao.PersonInfoDao;
import cn.shuangze.assetsms.dao.impl.PersonInfoDaoJDBCImpl;
import cn.shuangze.assetsms.dao.test.OptionType;
import cn.shuangze.assetsms.entity.AssetsInfo;
import cn.shuangze.assetsms.entity.PersonInfo;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Date;
import java.text.SimpleDateFormat;

public class ModifyPersonInfo extends JDialog implements ActionListener, ListSelectionListener {

    //定义DAO
    private PersonInfoDao personInfoDao;
    private OptionType flag;
    private Thread showThread;

    //定义所用的面板
    private JPanel northPanel = new JPanel();
    private JPanel centerPanel = new JPanel();

    //框架的大小
    private Dimension viewSize = new Dimension(600, 300);
    private Font font = new Font("Dialog", 0, 12);

    //定义图形界面元素
    private JLabel[] jLabel = new JLabel[6];
    private JTextField[] jTextField = new JTextField[6];

    private JButton modifyBtn = new JButton("修改");
    private JButton cancelBtn = new JButton("退出",new ImageIcon("images\\down.png"));
    private JComboBox<String> jComboBox = new JComboBox<>(new String[]{"男", "女"});

    //定义表格
    private JTable jTable;
    private DefaultTableModel tableModel;


    public ModifyPersonInfo(OptionType flag) {

        this.flag = flag;

        personInfoDao = new PersonInfoDaoJDBCImpl();

        showThread = new Thread(() -> {
            try {
                showTableData();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "窗口初始化错误，错误原因：" + e.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        //界面初始化
        init();

    }


    private void init() {
        Container contentPane = this.getContentPane();
        contentPane.setLayout(new BorderLayout());

        this.setModal(true);
        this.setSize(viewSize);

        //设置标题
        this.setTitle("人员信息修改");
        this.setResizable(false);

        //设置运行时窗口的位置
        this.setLocationRelativeTo(null);


        //北部面板的布局
        tableModel = new DefaultTableModel();  // 创建默认表格模式
        jTable = new MyJTable(tableModel);  // 创建表格 禁用编辑功能
        ListSelectionModel listSelectionModel = jTable.getSelectionModel();
        listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  // 设置表格选择模式为单一选择
        JScrollPane jScrollPane1 = new JScrollPane(jTable);  // 创建一个滚动面板，包含表格
        jScrollPane1.setPreferredSize(viewSize);  //设置滚动面板大小
        DefaultTableCellRenderer cr = new DefaultTableCellRenderer();
        cr.setHorizontalAlignment(JLabel.CENTER);  //表格内容居中
        jTable.setDefaultRenderer(Object.class, cr);
        //jTable.getTableHeader().setReorderingAllowed(false);  //禁止表头列拖动
        showThread.start();
        northPanel.add(jScrollPane1);


        //中部面板的布局
        JPanel line1 = new JPanel();
        JPanel line2 = new JPanel();
        for (int i = 0; i < jLabel.length; i++) {
            jLabel[i] = new JLabel();
            jLabel[i].setFont(font);

            jTextField[i] = new JTextField();
            jTextField[i].setColumns(12);
            jTextField[i].setEditable(false);

            if (i < jLabel.length / 2) {
                line1.add(jLabel[i]);
                if (i == 2) {
                    jComboBox.setPreferredSize(new Dimension(136, 20));
                    jComboBox.setFont(font);
                    jComboBox.setEnabled(false);
                    line1.add(jComboBox);
                } else {
                    line1.add(jTextField[i]);
                }

            } else {
                line2.add(jLabel[i]);
                line2.add(jTextField[i]);
            }
        }
        jLabel[0].setText("编号");
        jLabel[1].setText("姓名");
        jLabel[2].setText("性别");
        jLabel[3].setText("部门");
        jLabel[4].setText("职位");
        jLabel[5].setText("其他");

        centerPanel.setLayout(new GridLayout(2, 1));
        centerPanel.add(line1);
        centerPanel.add(line2);


        //南部面板的布局
        modifyBtn.setEnabled(false);
        modifyBtn.setFont(font);
        cancelBtn.setFont(font);

        JPanel line3 = new JPanel();
        line3.add(modifyBtn);
        line3.add(cancelBtn);

        if (flag == OptionType.MODIFY) {
            modifyBtn.setText("修改");
            modifyBtn.setIcon(new ImageIcon("images\\save.png"));
        } else {
            modifyBtn.setText("删除");
            modifyBtn.setIcon(new ImageIcon("images\\delete.png"));
        }

        contentPane.add(line3, BorderLayout.SOUTH);
        contentPane.add(northPanel, BorderLayout.NORTH);
        contentPane.add(centerPanel, BorderLayout.CENTER);


        //添加事件
        modifyBtn.addActionListener(this);
        cancelBtn.addActionListener(this);
        listSelectionModel.addListSelectionListener(this);
        jScrollPane1.addMouseListener(new TableMouseEvent());

    }


    private void showTableData() throws Exception {

        String[][] colValue = personInfoDao.findAll();
        String[] colName = {"人员编号", "姓名", "性别", "部门", "职位", "其他"};
        tableModel.setDataVector(colValue, colName);
        jTable.revalidate();  //刷新表格
    }


    private void setDefaultStatus() {

        for (JTextField j : jTextField) {
            j.setText(null);
            j.setEditable(false);
        }

        jComboBox.setEnabled(false);
        modifyBtn.setEnabled(false);
        jTable.getSelectionModel().clearSelection(); //取消表格选中
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        int selectedRow = jTable.getSelectedRow();
        if (selectedRow != -1) {

            for (int i = 0; i < jTextField.length; i++) {

                jTextField[i].setText((String) tableModel.getValueAt(selectedRow, i));

                if (flag == OptionType.MODIFY) {
                    jTextField[i].setEditable(true);
                }
            }

            if (jTextField[2].getText().equals("男")) {
                jComboBox.setSelectedIndex(0);
            } else if (jTextField[2].getText().equals("女")) {
                jComboBox.setSelectedIndex(1);
            }

            jTextField[0].setEditable(false);  //编号不可改

            modifyBtn.setEnabled(true);
            jComboBox.setEnabled(true);

        } else {
            setDefaultStatus();

        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object obj = e.getSource();

        if (obj == cancelBtn) {
            this.dispose();
        }

        try {

            if (obj == modifyBtn && flag == OptionType.MODIFY) {

                int personId = Integer.parseInt(jTextField[0].getText());
                String name = jTextField[1].getText();
                String sex = (jComboBox.getSelectedIndex() == 0) ? "男" : "女";
                String dept = jTextField[3].getText();
                String job = jTextField[4].getText();
                String other = jTextField[5].getText();

                if (name.equals("")) {

                    JOptionPane.showMessageDialog(this, "姓名不能为空！",
                            "修改失败", JOptionPane.WARNING_MESSAGE);
                    return;

                } else if (dept.equals("")) {

                    JOptionPane.showMessageDialog(this, "部门不能为空！",
                            "修改失败", JOptionPane.WARNING_MESSAGE);
                    return;

                } else if (job.equals("")) {

                    JOptionPane.showMessageDialog(this, "职位不能为空！",
                            "修改失败", JOptionPane.WARNING_MESSAGE);
                    return;

                } else {

                    personInfoDao.modify(new PersonInfo(personId, name, sex, dept, job, other));

                    JOptionPane.showMessageDialog(this, "信息修改成功！",
                            "修改成功", JOptionPane.INFORMATION_MESSAGE);
                }


            } else if (obj == modifyBtn && flag == OptionType.DELETE) {

                int i = 1;

                if (!jTextField[0].getText().equals("")) {
                    i = JOptionPane.showConfirmDialog(this, "确定要删除吗?",
                            null, JOptionPane.YES_NO_OPTION); //单击"确定"按钮,则返回值为0.
                }

                if (i == 0) {
                    personInfoDao.delete(Integer.parseInt(jTextField[0].getText()));
                    JOptionPane.showMessageDialog(this, "删除成功！",
                            "删除成功", JOptionPane.INFORMATION_MESSAGE);
                }
            }

            setDefaultStatus();
            showTableData();

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "数据库访问错误，错误原因：" + ex.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }


    class TableMouseEvent implements MouseListener {

        @Override
        public void mouseClicked(MouseEvent e) {
            setDefaultStatus();  //点击滚动面板空白处恢复默认状态
        }

        @Override
        public void mousePressed(MouseEvent e) {

        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    }

}
